<?php

namespace think\wework\Http;

use GuzzleHttp\Client;
use think\wework\Api\Token;
use GuzzleHttp\HandlerStack;

class ClientFactory
{
    /**
     * @param Token|null $token
     * @return Client
     */
    public static function create(Token $token = null): Client
    {
        $stack = HandlerStack::create();

        $stack->push(Middleware::retry());
        $stack->push(Middleware::response());

        if ($token instanceof Token) {
            $stack->push(Middleware::auth($token));
        }

        $options = [
            'base_uri' => 'https://qyapi.weixin.qq.com/cgi-bin/',
            'handler' => $stack
        ];
        $config = config('wework');
        if (!empty($config['proxy']) && $config['proxy'] === true) {
            $options['proxy'] = sprintf("%s:%s", env('PROXY.HOST'), env('PROXY.PORT'));
        }
        return new Client($options);
    }
}
